﻿namespace YunQue.WebApi.Common.Attributes
{
    /// <summary>
    /// 加载路由属性的类
    /// </summary>
    public class RouteAttributeLoader
    {
        private readonly IActionDescriptorCollectionProvider _actionDescriptorCollectionProvider;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="actionDescriptorCollectionProvider"></param>
        public RouteAttributeLoader(IActionDescriptorCollectionProvider actionDescriptorCollectionProvider)
        {
            _actionDescriptorCollectionProvider = actionDescriptorCollectionProvider;
        }
        
        /// <summary>
        /// 获取所有的路由地址以及对应的自定义Attribute
        /// </summary>
        /// <returns></returns>
        public Dictionary<string,List<Attribute>> LoadRouteAttributes()
        {
            var routeAttributes = new Dictionary<string, List<Attribute>>();

            // 获取所有的 Action 描述信息
            var actions = _actionDescriptorCollectionProvider.ActionDescriptors.Items;
            //获取指定的Attribute
            List<Type> attributeTypes = new List<Type>
            {
                typeof(APIPermissionAttribute),
                typeof(AllowAnonymousAttribute)
            };
            foreach (var action in actions)
            {
                if (action is ControllerActionDescriptor controllerAction)
                {
                    // 获取路由地址
                    var route = controllerAction.AttributeRouteInfo?.Template;

                    // 获取自定义 Attribute
                    var attributes = controllerAction.MethodInfo
                        .GetCustomAttributes(false)
                        .Where(attr => attr is Attribute && attributeTypes.Contains(attr.GetType()))
                        .Select(attr => attr as Attribute)
                        .ToList();

                    if (route != null && attributes.Count > 0)
                    {
                        route = route.ToLower();
                        routeAttributes[route] = attributes;
                    }
                }
            }
            return routeAttributes;
        }


    }
}
